<template>
	<!-- #ifndef APP-NVUE -->
	<canvas class="l-shrink" v-if="!canIUseOffscreenCanvas && canvasId" :canvas-id="canvasId" :id="canvasId" :style="[styles]" :hidpi="false"></canvas>
	<!-- #endif -->
</template>
<script lang="ts">
	// @ts-nocheck
	import {defineComponent, getCurrentInstance, watch, reactive, onUnmounted} from '@/uni_modules/lime-shared/vue';
	import {useCanvas, canIUseOffscreenCanvas} from './useCanvas'
	import {addUnit} from '@/uni_modules/lime-shared/addUnit'
	import {createImage} from '@/uni_modules/lime-shared/createImage'
	import {arrayBufferToFile} from '@/uni_modules/lime-shared/arrayBufferToFile'
	import {base64ToPath} from '@/uni_modules/lime-shared/base64ToPath'
	import {isBase64} from '@/uni_modules/lime-shared/isBase64'
	import {isBrowser} from '@/uni_modules/lime-shared/isBrowser'
	import {exif} from '@/uni_modules/lime-shared/exif'
	import {Shrink} from './shrink'
	export default defineComponent({
		setup(_,{expose}) {
			const context = getCurrentInstance()
			const canvasId = `l-shrink${context.uid}`
			let canvas = useCanvas(canvasId, context)
			
			const styles = reactive({width: '0px', height: '0px'})
			
			
			const options: any = {
				// 判断图片方向
				getImageOrientation(img: string) {
					return new Promise((resolve) => {
						exif.getData(img, function() {
							resolve(exif.getTag(this, 'Orientation')||1) 
						})
					})
				},
				dataToFile(data: any, name: string, type: string) {
					if (!data) throw new Error("data can not be null");
					if(isBrowser && !isBase64(data)) {
						return arrayBufferToFile(data, name, type)
					} else if(isBase64(data)) {
						return base64ToPath(data, name)
					} else {
						return data
					} 
				}
			}
			let stop = () => {}
			if(!canIUseOffscreenCanvas) {
				stop = watch(canvas, v => {
					styles.width = addUnit(v.width)
					styles.height = addUnit(v.height)
				})
				options.createCanvas = () => canvas
				options.createImage = createImage
			}
			const shrink = new Shrink(options)
			// #ifdef VUE3
			expose({
				compressImage: shrink.compressImage.bind(shrink) 
			})
			// #endif
			onUnmounted(stop)
			return {
				canvasId,
				canIUseOffscreenCanvas,
				styles,
				// #ifndef VUE3
				compressImage: shrink.compressImage.bind(shrink) 
				// #endif
			}
		}
	})
</script>
<style lang="scss">
	.l-shrink {
		position: fixed;
		left: 200%;
	}
</style>
